package io.renren.common.utils.sftp;

import com.jcraft.jsch.*;
import io.renren.common.utils.RedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Properties;

@Component
public class SFTPFactory {

    private Logger logger = LoggerFactory.getLogger(SFTPFactory.class);

    private ChannelSftp sftp = null;
    private Session sshSession = null;

    private static final SFTPFactory factory = new SFTPFactory();


    public static SFTPFactory getInstance(){
        return factory;
    }

    synchronized public ChannelSftp makeConnection(SFTPProperties properties,RedisUtils redisUtils){
        if (sftp !=null && sftp.isConnected()) {
            try {
                sftp.ls(properties.getBasePath());
            }catch (Exception ex) {
                redisUtils.set("ftp",null);
            } finally {
                this.connect(properties,redisUtils);
                return sftp;
            }
        }

        if( !Boolean.valueOf(redisUtils.get("ftp")) || sftp==null||!sftp.isConnected()){
            try {
                this.connect(properties,redisUtils);
            } catch (Exception e) {
                logger.error("ftp登录失败，检测登录ip，端口号，用户名密码是否正确，错误信息为"+e.getMessage());
                e.printStackTrace();
            }
            logger.info("ftp服务器连接成功");
        }
        return sftp;
    }

    /**
     * 通过SFTP连接服务器
     */
    public void connect(SFTPProperties properties,RedisUtils redisUtils) {
        try {
            JSch jsch = new JSch();
            jsch.getSession(properties.getUsername(), properties.getHost(), properties.getPort());
            sshSession = jsch.getSession(properties.getUsername(), properties.getHost(), properties.getPort());

            sshSession.setPassword(properties.getPassword());
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();

            Channel channel = sshSession.openChannel("sftp");
            channel.connect();

            sftp = (ChannelSftp) channel;
            redisUtils.set("ftp",true, 5*60);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭连接
     */
    public void disconnect() {
        if (this.sftp != null) {
            if (this.sftp.isConnected()) {
                this.sftp.disconnect();

            }
        }
        if (this.sshSession != null) {
            if (this.sshSession.isConnected()) {
                this.sshSession.disconnect();

            }
        }
    }

    public ChannelSftp getSftp() { return this.sftp;}
}
